// 营销组件调用方法封装
import { TipError } from '@common/tip';
const MKT = window.marketing;
import MD5 from '@common/md5';
import logger from '@common/logger';

import { envTarget } from '@common/environment';
import { Dialog } from 'vant';

/**
 * 初始化营销组件
 * @param {String} brandId 品牌ID
 * @param {String} storeId 门店ID，可以为空
 */
export const initMarket = (brandId, storeId='') => {
    logger.info('MKT => 初始化');
    if (!brandId || (brandId + '').trim() === '') {
        TipError('营销组件未初始化，缺少brandId');
        return;
    }
    MKT.init({
        _fetch: {},
        brandId: `${brandId}`,
        storeId: `${storeId}`,
        hostApp: MKT.appClients.MORDER,
        biz: MKT.bizs.FAST_FOOD, // 业态
        env: MKT.environments.DEBUG,
        strategy: {
            requestTimeout: 10,
        }
    });
    // MKT._setDebug({printLog: true});
    MKT.subscribeComponentNotify(MKT.componentErrorNotifies.RemoteDataFetchError, (error) => {
        Dialog.alert({
            title: '系统出错',
            message: '请刷新后重试',
        }).then(() => {
            // on close
        });
    });
    MKT.subscribeComponentNotify(MKT.componentErrorNotifies.RemoteTimeoutError, (error) => {
        Dialog.alert({
            title: '请求超时',
            message: '请刷新后重试',
        }).then(() => {
            // on close
        });
    });
};

// 会员相关
const MKT_MEMBER_INFO = MKT.memberInfoAgent();

/**
 * 获取会员详情
 * @param {String|Number} memberId 会员ID
 * @param {String|Number} groupId 体系ID
 */
export const getMemberInfo = async (memberId, groupId=0) => {
    logger.info('MKT => 获取会员信息', MKT_MEMBER_INFO);
    const channel = envTarget();
    try {
        const memberInfo = await MKT_MEMBER_INFO.getInfoInGroup(memberId, groupId, channel);
        return memberInfo;
    } catch (err) {
        logger.error(err.message);
    }
};

/**
 * 获取会员详情
 * @param {String} token 会员token
 * @param {String} type 类型
 */
export const getMemberInfoNew = async (token, type) => {
    logger.info('MKT => 获取会员信息 - 分场景获取', type);
    logger.debugger('执行获取会员信息 => token', token);
    logger.debugger('执行获取会员信息 => type', type);
    try {
        const memberInfo = await MKT_MEMBER_INFO.getMemberProperty(token, {
            businessType: type,
        });
        logger.success('MKT => 获取到的信息为：', memberInfo);
        return memberInfo;
    } catch (err) {
        logger.error('执行获取会员信息 => 错误', err);
        logger.error(err.message);
    }
};

/**
 * 更新用户信息
 * @param {String} token 用户信息token，营销侧
 * @param {Object} info 需要更新的信息
 */
export const updateMemberInfo = async (token, info) => {
    logger.info('MKT => 更新会员信息', info);
    try {
        const res = await MKT_MEMBER_INFO.updateInfo(token, info);
        logger.success('更新MemberInfo结果：', res);
        return res;
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 获取会员的所有优惠券
 * @param {String} token 用户信息token
 */
export const getMemberCouponList = async (token) => {
    try {
        const res = await MKT_MEMBER_INFO.getCouponList(token);
        logger.success('获取到的会员优惠券是：', res);
        return res;
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

// 会员账户相关
const MKT_MEMBER_ACCOUNT = MKT.memberAccountAgent();

/**
 * 分页获取会员卡账户变动信息
 * @param {Number} memberId 会员id
 * @param {Number|String} groupId 体系id
 * @param {Number} page 页码
 */
export const getAccountLog = async (memberId, groupId, page=1) => {
    logger.info('MKT => 余额变动记录', memberId, groupId, page);
    try {
        return await MKT_MEMBER_ACCOUNT.pageBalanceLog(memberId, groupId, {
            no: page,
        });
    } catch (error) {
        return [];
    }
};

/**
 * 分页获取会员卡积分变动信息
 * @param {Number} memberId 会员id
 * @param {Number|String} groupId 体系id
 * @param {Number} page 页码
 */
export const getCardIntegralLog = async (memberId, groupId, page=1) => {
    try {
        return await MKT_MEMBER_ACCOUNT.pageIntegralLog(memberId, groupId, {
            no: page,
        });
    } catch (error) {
        return false;
    }
};

const MKT_MEMBER_CARD = MKT.memberCardAgent();

/**
 * 会员领卡操作，领取门店相关的所有卡
 * @param {String} token 用户信息token，营销侧
 * @param {Number|String} storeId 门店id
 */
export const getMemberCardByStoreId = (token, storeId) => {
    logger.info('参数：', token, storeId);
    try {
        return MKT_MEMBER_CARD.ledCard(token, storeId);
    } catch (error) {
        // TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 获取指定体系的会员卡
 * @param {String} token 用户信息token，营销侧
 * @param {String|Number} groupId 体系id
 */
export const getMemberCardByGroupId = async (token, groupId) => {
    logger.info('MKT => 领体系默认卡，参数：', token, groupId);
    try {
        return await MKT_MEMBER_CARD.ledCardInGroup(token, groupId);
    } catch (error) {
        // TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 获取商城卡-领卡
 * @param {String} token 用户token
 * @param {String} brandId 品牌号
 */
export const getMemberShopCard = (token, brandId) => {
    logger.info('MKT => 获取会员商城卡', token, brandId);
    try {
        return MKT_MEMBER_CARD.getMemberCard(token, {
            brandId: brandId + '',
            businessType: 'emall',
        });
    } catch (error) {
        // TipError(dealErrorMessage(error));
        return false;
    }
};

const MKT_MEMBER_SEARCH = MKT.memberSearchAgent();

/**
 * 查询实体卡信息
 * @param {Number} cardNum 卡号
 * @param {Number} storeId 门店id
 */
export const getEntityCard = async (cardNum) => {
    try {
        return await MKT_MEMBER_SEARCH.queryMemberByCardUUID(cardNum);
    } catch (error) {
        TipError('会员卡信息查询失败');
        return {};
    }
};

const MKT_MEMBER_RAL = MKT.memberRegisterAndLoginAgent();

/**
 * 校验手机是否存在
 * @param {String} mobile 手机号
 */
export const checkMobileIsValidity = async (mobile) => {
    try {
        const val = await MKT_MEMBER_RAL.checkMobile(mobile);
        logger.info('校验手机的结果为：', val);
        return `${val.isPass}` === '0' ? true : false;
    } catch (error) {
        // TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 发送验证码
 * @param {String} mobile 手机号
 */
export const sendRegisterCode = (mobile) => {
    return MKT_MEMBER_RAL.sendVerifyCode(MKT.verificationCodeTypes.REGISTER_BY_MOBILE, mobile);
};
export const sendBindPhoneCode = (mobile) => {
    return MKT_MEMBER_RAL.sendVerifyCode(MKT.verificationCodeTypes.MEMBER_BIND_MOBILE, mobile);
};
export const sendCardBindCode = (mobile) => {
    return MKT_MEMBER_RAL.sendVerifyCode(MKT.verificationCodeTypes.CARD_BIND_MOBILE, mobile);
};
export const sendOpenCardCode = (mobile) => {
    return MKT_MEMBER_RAL.sendVerifyCode(MKT.verificationCodeTypes.ACTIVATE_CARD, mobile);
};
// 校验类型，自定义枚举
export const sendVerifyCode = (mobile) => {
    return MKT_MEMBER_RAL.sendVerifyCode('VERIFY_CODE', mobile);
};

const checkFunc = async (type, mobile, code) => {
    try {
        return await MKT_MEMBER_RAL.verifyCode(mobile, type, code);
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 校验手机验证码
 * @param {String} mobile 手机号
 * @param {String} code 验证码
 */
export const checkRegisterCode = async (mobile, code) => {
    return await checkFunc(MKT.verificationCodeTypes.REGISTER_BY_MOBILE, mobile, code);
};
export const checkBindPhoneCode = async (mobile, code) => {
    return await checkFunc(MKT.verificationCodeTypes.REGISTER_BY_MOBILE, mobile, code);
};
export const checkCardBindCode = async (mobile, code) => {
    return await checkFunc(MKT.verificationCodeTypes.CARD_BIND_MOBILE, mobile, code);
};
export const checkOpenCardCode = async (mobile, code) => {
    return await checkFunc(MKT.verificationCodeTypes.ACTIVATE_CARD, mobile, code);
};
// 校验类型，自定义枚举
export const checkVerifyCode = async (mobile, code) => {
    return await checkFunc('VERIFY_CODE', mobile, code);
};

// 密码
const MKT_PWD = MKT.memberSecurityAgent();

/**
 * 设置密码
 * @param {String} token 用户token
 * @param {String} password 密码
 */
export const setPassword = async (token, password) => {
    const pwd = MD5(password);
    try {
        return await MKT_PWD.resetPassword(token, false, pwd);
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 检查用户密码是否正确
 * @param {Number|String} memberId 会员id
 * @param {String} password 密码
 */
export const checkPassword = async (memberId, password) => {
    const pwd = MD5(password);
    try {
        return await MKT_PWD.validPassword(memberId, pwd);
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 修改用户免密状态
 * @param {String} token 用户信息token
 * @param {Boolean} flag 状态
 */
export const changeNoPwdStatus = async (token, flag) => {
    try {
        return await MKT_PWD.resetPassword(token, flag, '');
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

const dealErrorMessage = (error) => {
    const arr = error.message.split(':');
    return arr[arr.length - 1];
};

// 优惠相关
const MKT_ACTIVITY = MKT.esActivityAgent();

/**
 * 获取相应体系的充值活动
 * @param {String | Number} groupId 体系id
 */
export const getRechargeActivity = async (groupId) => {
    try {
        return await MKT_ACTIVITY.getTopupGradient(groupId);
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 获取是否存在绑定手机活动
 */
export const getIsHaveBindPhoneActivity = async () => {
    logger.info('MKT => 获取是否存在绑定手机活动');
    try {
        return await MKT_ACTIVITY.isHasAvailableActivityBy('K');
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

// 活动相关
const MKT_COUPONS_ACTIVITY = MKT.dActivityService ? MKT.dActivityService() : {};

/**
 * 通过活动id和用户token获取活动详情
 * @param {String} token 用户token
 * @param {String} activityId 活动id
 */
export const getCouponsActivity = async (token, activityId) => {
    logger.warn('MKT => 获取扫码领劵详情', token, activityId);
    try {
        return await MKT_COUPONS_ACTIVITY.check(token, activityId);
    } catch (error) {
        return false;
    }
};

/**
 * 用户参加活动
 * @param {String} token 用户token
 * @param {String} activityId 活动id
 */
export const joinCouponsActivity = async (token, activityId) => {
    logger.warn('MKT => 用户参与扫码领劵', token, activityId);
    try {
        return await MKT_COUPONS_ACTIVITY.getEquity(token, activityId);
    } catch (error) {
        TipError('参与活动失败，活动不可用！');
        return false;
    }
};

const MKT_MEMBER_BEHAVIOR = MKT.esMemberBehaviorAgent();

/**
 * 用户希望加入会员系统
 * @param {Number|String} memberId 用户id
 */
export const memberHopeJoin = async (memberId) => {
    try {
        await MKT_MEMBER_BEHAVIOR.wantJoinMemberGroup({
            memberId,
        });
        return true;
    } catch (error) {
        logger.error('期待加入失败');
        return false;
    }
};

const MKT_INTEGRAL_SHOP = MKT.integralExchangeService();

/**
 * 获取积分商城数据
 */
export const getIntegralShopData = async (param) => {
    try {
        return await MKT_INTEGRAL_SHOP.getAvailableCoupons(param);
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};

/**
 * 积分兑换优惠券
 */
export const integralExchangeCoupon = async (token, { groupId, cardTypeId, activityId, memberId }) => {
    try {
        await MKT_INTEGRAL_SHOP.exchangeCoupon(token, {
            groupId,
            cardTypeId,
            activityId,
            memberId,
        });
        return true;
    } catch (error) {
        TipError(dealErrorMessage(error));
        return false;
    }
};
